//
//  RemindSettingViewController.m
//  SmartCup
//
//  Created by Kendama on 2017/5/19.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "RemindSettingViewController.h"

@interface RemindSettingViewController ()

/** 提示 **/
@property(nonatomic,strong) UILabel *tipsLabel;
/** 开始 **/
@property(nonatomic,strong) UILabel *startLabel;
@property(nonatomic,strong) UILabel *endLabel;
@property(nonatomic,strong) UILabel *startTimeLabel;
@property(nonatomic,strong) UILabel *endTimeLabel;
@property(nonatomic,strong) UILabel *typeTitleLabel;
@property(nonatomic,strong) UILabel *typeLabel;
@property(nonatomic,strong) UILabel *numberTitleLabel;
@property(nonatomic,strong) UILabel *numberLabel;

/** 删除按钮 **/
@property(nonatomic,strong) UIButton *deleteButton;

/** 类型 **/
@property(nonatomic,assign) NSInteger remindType;

/** <#Description#> **/
@property(nonatomic,assign) NSInteger count;

@end

@implementation RemindSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)refreshBaseControlValue {
    [self setNavigationTitle:@"提醒编辑" titleColor:[UIColor whiteColor]];
    self.navigationBar.backgroundColor = [UIColor colorWithHexString:@"3E76F6"];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#F1F3F9"];
    [self setLeftButtonImage:[UIImage imageNamed:@"nav_icon_back"]];
    [self setRightButtonTitle:@"保存"];
    
    [self masLayout];
    
    if ([self.remindModel.type isEqualToString:@"喝水"]) {
        self.remindType = 0;
    } else if ([self.remindModel.type isEqualToString:@"吃药"]) {
        self.remindType = 1;
    }
    
//    NSLog(@"当天零点：%li",(long)[self zeroOfDate]);
}

#pragma mark -- 事件
- (void)onRightButtonClick:(id)sender {
    if ([self.typeLabel.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"主题不能为空"];
        return;
    }
    
    if ([self.startLabel.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"开始时间不能为空"];
        return;
    }
    
    if ([self.endTimeLabel.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"结束时间不能为空"];
        return;
    }
    
    
    if ([self.numberLabel.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"次数不能为空"];
        return;
    }
    
    if ([self compareStartTime:self.startTimeLabel.text andEndTime:self.endTimeLabel.text]) {
        [SVProgressHUD showErrorWithStatus:@"开始时间和结束时间距离太小"];
        return;
    }
    

    if ([self.startTimeLabel.text isEqualToString:self.endTimeLabel.text]) {
        [SVProgressHUD showErrorWithStatus:@"开始时间不能和结束时间相同"];
        return;
    }
    
    [self saveRemind];

}

- (void)saveRemind {
    if (self.remindModel != nil) {
        self.remindModel.startTime = self.startTimeLabel.text;
        self.remindModel.endTime = self.endTimeLabel.text;
        self.remindModel.count = self.count;
        self.remindModel.time = [[NSDate date] timeIntervalSince1970];
        self.remindModel.switchMark = YES;
        self.remindModel.type = self.typeLabel.text;
        
        if ([self.numberLabel.text isEqualToString:@"自动"]) {
            self.remindModel.count = 0;
        }
        
        if ([self.remindModel updateObject]) {
            [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            [self.navigationController popViewControllerAnimated:YES];
            
            if (self.updateBlock) {
                self.updateBlock();
            }
        }
        
    } else {
        RemindModel *remind = [[RemindModel alloc] init];
        remind.startTime = self.startTimeLabel.text;
        remind.endTime = self.endTimeLabel.text;
        remind.count = self.count;
        remind.time = [[NSDate date] timeIntervalSince1970];
        remind.switchMark = YES;
        remind.type = self.typeLabel.text;

        if ([remind insertObject]) {
            
            [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            [self.navigationController popViewControllerAnimated:YES];
            
            if (self.updateBlock) {
                self.updateBlock();
            }
        }
        
    }
}


//- (void)saveRemind {
//    NSMutableArray *array = [[NSMutableArray alloc] init];
//    [array addObjectsFromArray:DTCEXRACT_OBJECT(@"remind")];
//    if (self.dict != nil) { // 修改
//        for (int i = 0; i < array.count ;i++) {
////            NSDictionary *dic = array[i];
//            NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:array[i]];
//            if ([dic[@"time"] isEqualToString:self.dict[@"time"]]) {
//                [array removeObject:dic];
//                NSDictionary *dict = @{@"startTime":self.startTimeLabel.text,@"endTime":self.endTimeLabel.text,@"type":self.typeLabel.text,@"time":[NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]],@"count":self.count,@"switch":@"YES"};
//                [array addObject:dict];
//                DTCSAVE_OBJECT(array, @"remind");
//                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
//                [self.navigationController popViewControllerAnimated:YES];
//                
//                if (self.updateBlock) {
//                    self.updateBlock();
//                }
//            }
//        }
//        
//    } else { // 新增
//        NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"startTime":self.startTimeLabel.text,@"endTime":self.endTimeLabel.text,@"type":self.typeLabel.text,@"time":[NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]],@"count":self.count,@"switch":@"YES"}];
//
////        NSDictionary *dict = @{@"startTime":self.startTimeLabel.text,@"endTime":self.endTimeLabel.text,@"type":self.typeLabel.text,@"time":[NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]],@"count":self.count,@"switch":@"YES"};
//        [array addObject:dict];
//        DTCSAVE_OBJECT(array, @"remind");
//        NSLog(@"array=%@",array);
//        [SVProgressHUD showSuccessWithStatus:@"保存成功"];
//        [self.navigationController popViewControllerAnimated:YES];
//        
//        if (self.updateBlock) {
//            self.updateBlock();
//        }
//    }
//}

- (BOOL)compareStartTime:(NSString *)startTime andEndTime:(NSString *)endTime {
    NSInteger start = [self getYearMouthDayWithTime:startTime];
    NSInteger end = [self getYearMouthDayWithTime:endTime];
    
    if (start > end) { // 开始时间大于结束时间
        return YES;
    } else if ((end - start)/60 < self.count) {
        return YES;
    } else {
        return NO;
    }
}



// 将某个时间点转换成时间戳
- (NSInteger)getYearMouthDayWithTime:(NSString *)time {
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *formatTime = [NSString stringWithFormat:@"%@ %@",[dateFormatter stringFromDate:date],time];
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"]; //(@"YYYY-MM-dd hh:mm:ss") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate* date2 = [formatter dateFromString:formatTime]; //------------将字符串按formatter转成nsdate
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[date2 timeIntervalSince1970]] integerValue];
    return timeSp;
}



- (void)didClickDeleteButton {
    if ([self.remindModel deleteObject]){
        [SVProgressHUD showSuccessWithStatus:@"删除成功"];
        [self.navigationController popViewControllerAnimated:YES];
        
        if (self.updateBlock) {
            self.updateBlock();
        }
    }
}

- (void)showStartTimeChoose {
    NSDate *date = [NSDate date];
    [[DTPickerManager shareManager]showDate:date pickerWithTimeAndPicker:^(NSArray *arr) {
        
    } andConfirm:^(NSArray *arr) {
        self.startTimeLabel.text = [NSString stringWithFormat:@"%.2d:%.2d",[arr[0]intValue],[arr[1]intValue]];
    }];
}

- (void)showEndTimeChoose {
    NSDate *date = [NSDate date];
    [[DTPickerManager shareManager]showDate:date pickerWithTimeAndPicker:^(NSArray *arr) {
        
    } andConfirm:^(NSArray *arr) {
        self.endTimeLabel.text = [NSString stringWithFormat:@"%.2d:%.2d",[arr[0]intValue],[arr[1]intValue]];
    }];
}

- (void)showTypeChoose{
    [[DTPickerManager shareManager] showPickerWithTypeAndPicker:^(NSArray *arr) {
        
    } andConfirm:^(NSArray *arr) {
        self.typeLabel.text = arr[0];
        if ([arr[0] isEqualToString:@"喝水"]) {
            self.count = 0;
            self.remindType = 0;
            self.tipsLabel.text = @"在此时间段内，将会根据喝水次数间隔提醒";
        } else if ([arr[0] isEqualToString:@"吃药"]) {
            self.remindType = 1;
            self.numberLabel.text = @"3次";
            self.count = 3;
            self.tipsLabel.text = @"在此时间段内，将会根据吃药次数间隔提醒";
        }
    }];
}

- (void)showCountChoose{
    [[DTPickerManager shareManager] showWaterType:self.remindType pickerWithTimeAndPicker:^(NSArray *arr) {
        
    } andConfirm:^(NSArray *arr) {
        if ([arr[0] isEqualToString:@"自动"]) {
            self.numberLabel.text = arr[0];
            self.count = 0;
        } else {
            self.numberLabel.text = [NSString stringWithFormat:@"%@次",arr[0]];
            self.count = [arr[0] integerValue];
        }

    }];


}

- (void)masLayout {
    __weak UIView *superView = self.view;
    int count = 5;
    UIView *lastView = nil;
    //    NSArray *array = @[self.tipsLabel,self.startTimeLabel,self.sexLabel,self.heightLabel,self.weightLabel,self.ageLabel];
    for(int i = 0;i < count;++i ){
        //创建一个View
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor whiteColor];
        [superView addSubview:view];
        
        UIView *line = [[UIView alloc] init];
        line.backgroundColor = [UIColor colorWithHexString:@"#D0D3DC"];
        
        UIImageView *arrow = [[UIImageView alloc] init];
        arrow.image = [UIImage imageNamed:@"icon_more_nor"];
        
        [superView addSubview:line];
        [view addSubview:arrow];
        //        [view addSubview:title];
        //向subView添加约束
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.equalTo(self.view);
            make.height.mas_equalTo(px1920Height(2));
            
            //判断是否有前一个子View
            if ( lastView ) {
                //如果有前一个View，上边界和前一个View的下边界紧贴
                make.top.mas_equalTo(lastView.mas_bottom).with.offset(px1920Height(170));
            } else {
                //如果没有前一个View，上边界和container的下边界紧贴
                make.top.mas_equalTo(self.view.mas_top).with.offset(64+px1920Height(170));
            }
        }];
        
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(line);
            make.width.equalTo(self.view);
            make.height.mas_equalTo(px1920Height(170));
        }];
        
        [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(line).with.offset(-px1920Height(85));
            make.right.equalTo(self.view).with.offset(-px1080Width(30));
            make.width.height.mas_equalTo(px1080Width(80));
        }];
        
        if (i == 0) {
            [view addSubview:self.typeTitleLabel];
            [view addSubview:self.typeLabel];
            
            [self.typeTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.width.mas_equalTo(px1080Width(100));
                make.height.mas_equalTo(px1080Width(100));
                make.left.equalTo(self.view).with.offset(px1080Width(52));
            }];
            
            [self.typeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.left.equalTo(self.typeTitleLabel.mas_right);
                make.right.equalTo(arrow.mas_left);
                make.height.mas_equalTo(px1920Height(200));
            }];
        } else if (i == 1) {
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(line);
                make.width.mas_equalTo(px1080Width(0));
                make.height.mas_equalTo(px1920Height(0));
            }];
            
            [arrow mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.right.equalTo(self.view).with.offset(-px1080Width(30));
                make.width.height.mas_equalTo(px1080Width(0));
            }];
            
            [superView addSubview:self.tipsLabel];
            [self.tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.bottom.equalTo(line).with.offset(-px1920Height(20));
                make.left.equalTo(superView).with.offset(px1080Width(50));
                make.right.equalTo(superView).with.offset(-px1080Width(50));
                make.height.mas_equalTo(px1080Width(50));
            }];
        } else if (i == 2) {

            
            [view addSubview:self.startLabel];
            [view addSubview:self.startTimeLabel];
            
            [self.startLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.width.mas_equalTo(px1080Width(100));
                make.height.mas_equalTo(px1080Width(100));
                make.left.equalTo(self.view).with.offset(px1080Width(52));
            }];
            
            [self.startTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.left.equalTo(self.startLabel.mas_right);
                make.right.equalTo(arrow.mas_left);
                make.height.mas_equalTo(px1920Height(200));
            }];
            
        } else if (i == 3){
            
            [view addSubview:self.endLabel];
            [view addSubview:self.endTimeLabel];
            
            [self.endLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.width.mas_equalTo(px1080Width(100));
                make.height.mas_equalTo(px1080Width(100));
                make.left.equalTo(self.view).with.offset(px1080Width(52));
            }];
            
            [self.endTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.left.equalTo(self.endLabel.mas_right);
                make.right.equalTo(arrow.mas_left);
                make.height.mas_equalTo(px1920Height(200));
            }];
            
        } else if (i == 4){
            
            [view addSubview:self.numberLabel];
            [view addSubview:self.numberTitleLabel];
            
            [self.numberTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.width.mas_equalTo(px1080Width(100));
                make.height.mas_equalTo(px1080Width(100));
                make.left.equalTo(self.view).with.offset(px1080Width(52));
            }];
            
            [self.numberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(line).with.offset(-px1920Height(85));
                make.left.equalTo(self.numberTitleLabel.mas_right);
                make.right.equalTo(arrow.mas_left);
                make.height.mas_equalTo(px1920Height(200));
            }];
            
        }
        //保存前一个View
        lastView = line;
    }
    
    
    [self.deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(lastView.mas_bottom).with.offset(px1920Height(451));
        make.left.mas_equalTo(superView).with.offset(px1080Width(48));
        make.right.mas_equalTo(superView).with.offset(-px1080Width(48));
        make.height.mas_equalTo(px1920Height(148));
    }];
    
    
    if (self.type == 1) {
        self.deleteButton.hidden = YES;
    } else {
        self.deleteButton.hidden = NO;
    }

}




#pragma mark -- 懒加载
- (UILabel *)startLabel
{
    if(!_startLabel)
    {
        //        __weak UIView *superView = self.view;
        _startLabel = [[UILabel alloc]init];
        //        [superView addSubview:_startLabel];
        [_startLabel setFont:[UIFont systemFontOfSize:px1080Width(36)]];
        [_startLabel setTextColor:[UIColor colorWithHexString:@"#3E76F6"]];
        _startLabel.text = @"始";
    }
    return _startLabel;
}
- (UILabel *)endLabel
{
    if(!_endLabel)
    {
        //        __weak UIView *superView = self.view;
        _endLabel = [[UILabel alloc]init];
        //        [superView addSubview:_endLabel];
        [_endLabel setFont:[UIFont systemFontOfSize:px1080Width(36)]];
        [_endLabel setTextColor:[UIColor colorWithHexString:@"F6663E"]];
        _endLabel.text = @"终";
    }
    return _endLabel;
}
- (UILabel *)startTimeLabel
{
    if(!_startTimeLabel)
    {
        //        __weak UIView *superView = self.view;
        _startTimeLabel = [[UILabel alloc]init];
        //        [superView addSubview:_startTimeLabel];
        [_startTimeLabel setFont:[UIFont systemFontOfSize:px1080Width(64)]];
        [_startTimeLabel setTextColor:[UIColor colorWithHexString:@"585D6D"]];
        _startTimeLabel.text = self.dict[@"startTime"];
        _startTimeLabel.userInteractionEnabled = YES;
        [_startTimeLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showStartTimeChoose)]];
        if (self.remindModel == nil) {
            _startTimeLabel.text = @"08:00";
        } else {
            _startTimeLabel.text = self.remindModel.startTime;
        }
        
    }
    return _startTimeLabel;
}
- (UILabel *)endTimeLabel
{
    if(!_endTimeLabel)
    {
        //        __weak UIView *superView = self.view;
        _endTimeLabel = [[UILabel alloc]init];
        //        [superView addSubview:_endTimeLabel];
        [_endTimeLabel setFont:[UIFont systemFontOfSize:px1080Width(64)]];
        [_endTimeLabel setTextColor:[UIColor colorWithHexString:@"585D6D"]];
        _endTimeLabel.text = self.dict[@"endTime"];
        _endTimeLabel.userInteractionEnabled = YES;
        [_endTimeLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showEndTimeChoose)]];
        if (self.remindModel == nil) {
            _endTimeLabel.text = @"22:00";
        } else {
            _endTimeLabel.text = self.remindModel.endTime;
        }
    }
    return _endTimeLabel;
}
- (UILabel *)tipsLabel
{
    if(!_tipsLabel)
    {
        //        __weak UIView *superView = self.view;
        _tipsLabel = [[UILabel alloc]init];
        //        [superView addSubview:_tipsLabel];
        [_tipsLabel setFont:[UIFont systemFontOfSize:px1080Width(36)]];
        [_tipsLabel setTextColor:[UIColor colorWithHexString:@"9295A0"]];
        _tipsLabel.text = @"在此时间段内，将会根据喝水次数间隔提醒";
    }
    return _tipsLabel;
}

- (UIButton *)deleteButton
{
    if(!_deleteButton)
    {
        __weak UIView *superView = self.view;
        _deleteButton = [[UIButton alloc]init];
        [superView addSubview:_deleteButton];
        [_deleteButton setTitle:@"删除" forState:UIControlStateNormal];
        [_deleteButton setBackgroundImage:[UIImage imageNamed:@"button_delete_nor"] forState:UIControlStateNormal];
        [_deleteButton setBackgroundImage:[UIImage imageNamed:@"button_delete_nor"] forState:UIControlStateHighlighted];
        [_deleteButton.titleLabel setFont:[UIFont systemFontOfSize:px1080Width(52)]];
        [_deleteButton addTarget:self action:@selector(didClickDeleteButton) forControlEvents:UIControlEventTouchUpInside];

    }
    return _deleteButton;
}


- (UILabel *)typeTitleLabel
{
    if(!_typeTitleLabel)
    {
        UIView *superView = self.view;
        _typeTitleLabel = [[UILabel alloc]init];
        [superView addSubview:_typeTitleLabel];
        [_typeTitleLabel setFont:[UIFont systemFontOfSize:px1080Width(42)]];
        [_typeTitleLabel setTextColor:[UIColor colorWithHexString:@"585D6D"]];
        _typeTitleLabel.text = @"主题";
    }
    return _typeTitleLabel;
}
- (UILabel *)typeLabel
{
    if(!_typeLabel)
    {
        UIView *superView = self.view;
        _typeLabel = [[UILabel alloc]init];
        [superView addSubview:_typeLabel];
        [_typeLabel setFont:[UIFont systemFontOfSize:px1080Width(42)]];
        [_typeLabel setTextColor:[UIColor colorWithHexString:@"585D6D"]];
        _typeLabel.textAlignment = NSTextAlignmentRight;
        if (self.remindModel == nil) {
            _typeLabel.text = @"喝水";
        } else {
            _typeLabel.text = self.remindModel.type;
        }
        _typeLabel.userInteractionEnabled = YES;
        [_typeLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showTypeChoose)]];

    }
    return _typeLabel;
}
- (UILabel *)numberTitleLabel
{
    if(!_numberTitleLabel)
    {
        UIView *superView = self.view;
        _numberTitleLabel = [[UILabel alloc]init];
        [superView addSubview:_numberTitleLabel];
        [_numberTitleLabel setFont:[UIFont systemFontOfSize:px1080Width(42)]];
        [_numberTitleLabel setTextColor:[UIColor colorWithHexString:@"585D6D"]];
        _numberTitleLabel.text = @"次数";
    }
    return _numberTitleLabel;
}
- (UILabel *)numberLabel
{
    if(!_numberLabel)
    {
        UIView *superView = self.view;
        _numberLabel = [[UILabel alloc]init];
        [superView addSubview:_numberLabel];
        [_numberLabel setFont:[UIFont systemFontOfSize:px1080Width(42)]];
        [_numberLabel setTextColor:[UIColor colorWithHexString:@"585D6D"]];
        _numberLabel.textAlignment = NSTextAlignmentRight;
        _numberLabel.userInteractionEnabled = YES;
        if (self.remindModel == nil || self.remindModel.count == 0) {
            _numberLabel.text = @"自动";
            self.count = 0;
        } else {
            _numberLabel.text = [NSString stringWithFormat:@"%ld次",(long)self.remindModel.count];
        }
        [_numberLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showCountChoose)]];

    }
    return _numberLabel;
}


- (NSInteger)count
{
    if(!_count)
    {
        _count = self.remindModel.count;
    }
    return _count;
}


@end
